import requests
from datetime import datetime
from python_depend.mysql_pool import MySQLPool


def get_coinmarketcap_data():
    """调用CoinMarketCap API获取全球加密货币指标数据"""
    url = "https://pro-api.coinmarketcap.com/v1/global-metrics/quotes/latest"
    headers = {
        "X-CMC_PRO_API_KEY": "e166859b-aa6e-4932-87cf-83f3be9e281b",
        "Accept": "application/json"
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        # 检查API返回状态
        if data.get('status', {}).get('error_code') != 0:
            error_msg = data.get('status', {}).get('error_message', '未知错误')
            raise Exception(f"API请求失败: {error_msg}")
        return data.get('data', {})
    except requests.exceptions.RequestException as e:
        raise Exception(f"请求发生错误: {str(e)}")


def calculate_other_dominance(btc_dominance, eth_dominance):
    """计算其他加密货币的占比"""
    return 100 - btc_dominance - eth_dominance


def calculate_percentage_change(current, previous):
    """
    计算涨跌幅百分比
    公式: ((当前值 -  previous值) / previous值) * 100
    """
    if previous == 0:
        return 0  # 避免除以零错误
    return ((current - previous) / previous) * 100


def get_hourly_timestamp():
    """获取当前时间到小时级别的时间戳（毫秒）"""
    # 获取当前时间
    now = datetime.now()
    # 截断到小时级别
    hourly = now.replace(minute=0, second=0, microsecond=0)
    # 转换为毫秒级时间戳
    return int(hourly.timestamp() * 1000)


def insert_into_database(data):
    """将处理后的数据插入到数据库"""
    # 提取USD报价数据
    usd_quote = data.get('quote', {}).get('USD', {})
    # 提取所需字段
    total_market_cap = usd_quote.get('total_market_cap')
    total_market_cap_yesterday = usd_quote.get('total_market_cap_yesterday')
    total_volume_24h = usd_quote.get('total_volume_24h')
    eth_dominance = data.get('eth_dominance')
    btc_dominance = data.get('btc_dominance')
    btc_dominance_yesterday = data.get('btc_dominance_yesterday')
    eth_dominance_yesterday = data.get('eth_dominance_yesterday')
    eth_dominance_24h_change = data.get('eth_dominance_24h_percentage_change')
    btc_dominance_24h_change = data.get('btc_dominance_24h_percentage_change')
    # 计算衍生字段
    total_market_cap_chg = calculate_percentage_change(total_market_cap,
                                                       total_market_cap_yesterday) if total_market_cap and total_market_cap_yesterday else None
    # 计算其他加密货币占比
    other_dominance = calculate_other_dominance(btc_dominance,
                                                eth_dominance) if btc_dominance and eth_dominance else None
    # 计算其他加密货币占比涨跌幅百分比
    yesterday_other = calculate_other_dominance(btc_dominance_yesterday,
                                                eth_dominance_yesterday) if btc_dominance_yesterday and eth_dominance_yesterday else None
    other_dominance_chg = other_dominance-yesterday_other if other_dominance  and yesterday_other  else None
    # 获取记录时间（小时级别时间戳）
    record_time = get_hourly_timestamp()
    # 获取当前时间（用于create_time和update_time）
    current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 插入SQL语句
    insert_query = """
    INSERT INTO crypto_global_indicator 
    (total_market_cap, total_market_cap_chg, total_volume_24h, 
     eth_dominance, eth_dominance_chg, btc_dominance, 
     btc_dominance_chg, other_dominance, other_dominance_chg, 
     record_time, create_time, update_time)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    ON DUPLICATE KEY UPDATE
        total_market_cap = VALUES(total_market_cap),
        total_market_cap_chg = VALUES(total_market_cap_chg),
        total_volume_24h = VALUES(total_volume_24h),
        eth_dominance = VALUES(eth_dominance),
        eth_dominance_chg = VALUES(eth_dominance_chg),
        btc_dominance = VALUES(btc_dominance),
        btc_dominance_chg = VALUES(btc_dominance_chg),
        other_dominance = VALUES(other_dominance),
        other_dominance_chg = VALUES(other_dominance_chg),
        update_time = VALUES(update_time)
    """

    insert_market_query = """
    INSERT INTO crypto_global_market_indicator 
    (total_market_cap, total_market_cap_chg, total_volume_24h, 
     eth_dominance, eth_dominance_chg, btc_dominance, 
     btc_dominance_chg, other_dominance, other_dominance_chg, 
     record_time, create_time, update_time)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    ON DUPLICATE KEY UPDATE
        total_market_cap = VALUES(total_market_cap),
        total_market_cap_chg = VALUES(total_market_cap_chg),
        total_volume_24h = VALUES(total_volume_24h),
        eth_dominance = VALUES(eth_dominance),
        eth_dominance_chg = VALUES(eth_dominance_chg),
        btc_dominance = VALUES(btc_dominance),
        btc_dominance_chg = VALUES(btc_dominance_chg),
        other_dominance = VALUES(other_dominance),
        other_dominance_chg = VALUES(other_dominance_chg),
        update_time = VALUES(update_time)
    """

    # 准备数据
    data_tuple = (
        total_market_cap if total_market_cap is not None else None,
        total_market_cap_chg if total_market_cap_chg is not None else None,
        total_volume_24h if total_volume_24h is not None else None,
        eth_dominance if eth_dominance is not None else None,
        eth_dominance_24h_change if eth_dominance_24h_change is not None else None,
        btc_dominance if btc_dominance is not None else None,
        btc_dominance_24h_change if btc_dominance_24h_change is not None else None,
        other_dominance if other_dominance is not None else None,
        other_dominance_chg if other_dominance_chg is not None else None,
        record_time,
        current_datetime,
        current_datetime
    )
    # 连接数据库并插入数据
    mysql_pool = MySQLPool.get_pool('feature_quote_data')
    try:
        connection = mysql_pool.connection()
        with connection.cursor() as cursor:
            cursor.execute(insert_query, data_tuple)
            # 插入新表
            cursor.execute(insert_market_query, data_tuple)
            connection.commit()
    except Exception as e:
        print(f"写入失败: {e}")


def main():
    try:
        # 获取数据
        print("GET DATA FROM CoinMarketCap API")
        crypto_data = get_coinmarketcap_data()
        if not crypto_data:
            print("未获取到有效数据，退出程序")
            return
        # 插入数据库
        print(f"get data is {crypto_data} Write  the data into the database")
        insert_into_database(crypto_data)
        print("success")
    except Exception as e:
        print(f"程序执行出错: {str(e)}")


if __name__ == "__main__":
    MySQLPool.initialize()
    main()
    MySQLPool.close_all()
